package org.example.blogserver.system.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import org.example.blogserver.system.annotation.PreAuthorize;
import org.example.blogserver.system.jwt.JwtUtil;
import org.example.blogserver.system.jwt.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.List;

@Component//
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("拦截到请求：" + requestURI);
        if ("front".equals(request.getHeader("requestType"))){
            return true;//如果是前台门户的请求头,说明是前台门户的请求,暂时放行
        }
        String token = request.getHeader("token");

        if (StrUtil.isBlank(token)){
            response.setContentType(ContentType.JSON.toString());//设置内容类型,告诉别人我要返回自定义的json字符串
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");//{"success":false,"message":"toLogin"}
            return false;//不放行
        }

        try {
            Payload payload = JwtUtil.parseJwtToken(token);
            //1.拿到用户请求的权限
            //拿到注解上面的sn
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            PreAuthorize methodAnnot = handlerMethod.getMethodAnnotation(PreAuthorize.class);
            if(methodAnnot == null){
                return true;
            }
            String sn = methodAnnot.sn();
            //2.看用户是否有这个权限
            List<String> ownPermiss = payload.getPermissions();
            if (!ownPermiss.contains(sn)){
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().println("{\"success\":false,\"message\":\"无权限\"}");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType(ContentType.JSON.toString());//设置内容类型,告诉别人我要返回自定义的json字符串
            response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");//{"success":false,"message":"toLogin"}
            return false;//不放行
        }
        return true;//放行
    }
}
